import datetime
import uuid

from django.shortcuts import HttpResponse, render, redirect
from web.forms.account import RegisterForm, SendSmsForm, SmsLoginForm, LoginForm
from django.http import JsonResponse
from web import models


def register(request):
    """ 注册用户  """
    if request.method == 'GET':
        form = RegisterForm()
        return render(request, 'web/register.html', {'register_form': form})
    else:
        form = RegisterForm(data=request.POST)
        if form.is_valid():
            instance = form.save()  # instance是前端表单传过来的数据
            # 创建交易记录
            policy_object = models.PricePolicy.objects.filter(category=1, title='个人免费版',).first()
            models.Transaction.objects.create(
                status=2,
                order=str(uuid.uuid4()),
                user=instance,
                price_policy=policy_object,
                count=0,
                price=0,
                start_datetime=datetime.datetime.now()
            )
            return JsonResponse({'status': True, 'data': '/login/'})
        return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    """ 发送短信后端接口 """
    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def sms_login(request):
    """ 短信验证码登录 """
    if request.method == 'GET':
        form = SmsLoginForm()
        return render(request, 'web/sms_login.html', {'sms_login_form': form})
    else:
        form = SmsLoginForm(data=request.POST)
        if form.is_valid():
            # 用户输入正确，登录成功
            mobile_phone = form.cleaned_data['mobile_phone']

            # 把用户名写入到session中
            user_object = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60 * 60 * 24 * 14)

            return JsonResponse({"status": True, 'data': "/index/"})

        return JsonResponse({"status": False, 'error': form.errors})


def login(request):
    """ 用户名密码登录 """
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'web/login.html', {'login_form': form})
    else:
        form = LoginForm(request, data=request.POST)
        if form.is_valid():
            from django.db.models import Q
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
                password=password).first()
            if user_object:
                # 登录成功
                request.session['user_id'] = user_object.id
                request.session.set_expiry(60 * 60 * 24 * 14)

                return redirect('index')

            form.add_error('username', '用户名或密码错误')
            return render(request, 'web/login.html', {'login_form': form})
        else:
            return render(request, 'web/login.html', {'login_form': form})


def image_code(request):
    from utils.image_code import check_code
    from io import BytesIO
    image_object, code = check_code()
    # 将code以image_code 为键保存在session中，同时封装一个随机字符串座位cookie返回给客户端
    request.session['image_code'] = code
    request.session.set_expiry(60)  # 主动修改session的过期时间为60s

    stream = BytesIO()
    image_object.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.flush()
    return redirect('index')
